package com.superm.realm;

import com.superm.entity.Emp;
import com.superm.entity.Permission;
import com.superm.entity.Role;
import com.superm.entity.RolePermission;
import com.superm.service.EmpService;
import com.superm.service.RoleService;
import com.superm.service.impl.EmpServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CustomRealm extends AuthorizingRealm{
	@Autowired
	private EmpService empService;
	@Autowired
	private RoleService roleService;
	//授权:默认每进行一次权限的判断，授权方法就会执行一次
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		List<String> roleStr = new ArrayList<String>();
		List<String> permission = new ArrayList<String>();
		System.out.println("进入了授权");
		//获取授权对象中的信息
		Emp emp = (Emp)principal.getPrimaryPrincipal();
		emp.getRoles().forEach(roles->{
			//放入角色
			roleStr.add(roles.getrName());
			roles.getPermissions().forEach(pers->{
				//放入权限
				permission.add(pers.getCode());
			});
		});
		System.out.println(roleStr);
		//放入认证对象
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRoles(roleStr);
		simpleAuthorizationInfo.addStringPermissions(permission);
		return simpleAuthorizationInfo;
	}
	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取认证主体
		String principal = token.getPrincipal().toString();
		Emp emp = new Emp();
		emp.seteName(principal);
		emp = empService.empLogin(emp);
		if (emp==null){
			//账号不存在
			return null;
		}
		return new SimpleAuthenticationInfo(emp,emp.getePassword(),ByteSource.Util.bytes(emp.geteSalt()),this.getName());
	}
}
	